<template>
  <el-main>
    <el-form ref="seachform" :model="parms" label-width="80px" :inline="true" size="small">
      <el-form-item label="角色名称">
        <el-input v-model="parms.name" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="searchList">查询</el-button>
        <el-button style="color: #ff7670" icon="el-icon-delete" @click="cacelList">取消</el-button>
        <el-button v-if="hasPerm('sys:role:add')" type="primary" icon="el-icon-plus" @click="addRole">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :height="tableHeight" :data="roleList" border stripe>
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="remark" label="角色备注" />
      <el-table-column label="操作" align="center" width="290">
        <template slot-scope="scope">
          <el-button v-if="hasPerm('sys:role:edit')" icon="el-icon-edit" type="primary" size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button v-if="hasPerm('sys:role:assign')" icon="el-icon-setting" type="primary" size="small" @click="assignRole(scope.row)">分配权限</el-button>
          <el-button v-if="hasPerm('sys:role:delete')" icon="el-icon-delete" type="danger" size="small" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page.sync="parms.currentPage" :page-sizes="[10, 20, 40, 80, 100]" :page-size="parms.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="parms.total" background @size-change="sizeChange" @current-change="currentChange" />
    <!-- 新增或编辑弹框 -->
    <sys-dialog :title="addDialog.title" :height="addDialog.height" :width="addDialog.width" :visible="addDialog.visible" @onClose="onClose" @onConfirm="onConfirm">
      <div slot="content">
        <el-form ref="addRoleForm" :model="addRoleModule" :rules="rules" label-width="80px" :inline="true" size="small">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="addRoleModule.name" />
          </el-form-item>
          <el-form-item label="角色备注">
            <el-input v-model="addRoleModule.remark" />
          </el-form-item>
        </el-form>
      </div>
    </sys-dialog>
    <!-- 分配权限弹框 -->
    <sys-dialog :title="assignDialog.title" :height="assignDialog.height" :width="assignDialog.width" :visible="assignDialog.visible" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
      <div slot="content">
        <el-tree ref="assignTree" :data="assignTreeData" node-key="id" :props="defaultProps" empty-text="暂无事数据" :show-checkbox="true" :highlight-current="true" default-expand-all @node-click="handleNodeClick" />
      </div>
    </sys-dialog>
  </el-main>
</template>

<script>
import SysDialog from '@/components/system/SysDialog'
// 判断是否是末级的js方法
import leafUtils from '@/utils/leafUtils'
import {
  getRoleListApi,
  addRoleApi,
  editRoleApi,
  deleteRoleApi,
  getAssignTreeApi,
  assignSaveApi
} from '@/api/role'
export default {
  components: {
    SysDialog
  },
  data () {
    return {
      // 动态计算高度
      screenHeight: document.body.clientHeight,
      // 树属性配置
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 分配权限树数据域
      assignTreeData: [],
      // 角色id
      roleId: '',
      // 分配权限弹框属性
      assignDialog: {
        title: '',
        height: 450,
        width: 300,
        visible: false
      },
      // 表单验证
      rules: {
        name: [
          {
            required: true,
            trigger: 'change',
            message: '请填写角色名称'
          }
        ]
      },
      // 新增或编辑表单数据域
      addRoleModule: {
        id: '', // 编辑时候使用
        editType: '', // 标识新增或编辑  0：新增 1：编辑
        name: '',
        remark: '',
        createUser: this.$store.getters.userId
      },
      // 新增或编辑弹框属性
      addDialog: {
        title: '',
        height: 150,
        width: 610,
        visible: false
      },
      // 表格高度
      tableHeight: 0,
      // 角色列表数据
      roleList: [],
      // 查询参数
      parms: {
        currentPage: 1, // 当前是第几页
        pageSize: 10, // 每页查询条数
        userId: this.$store.getters.userId,
        total: 0,
        name: ''
      }
    }
  },
  watch: {
    screenHeight (val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenHeight = val
        this.timer = true
        const that = this
        setTimeout(function () {
          // 打印screenWidth变化的值
          // console.log(that.screenHeight)
          that.tableHeight = that.screenHeight - 210
          that.timer = false
        }, 400)
      }
    }
  },
  created () {
    this.getRoleList()
  },
  mounted () {
    const that = this
    window.onresize = () => {
      return (() => {
        that.screenHeight = document.body.clientHeight
      })()
    }
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 210
    })
  },
  methods: {
    // 树的节点点击事件
    handleNodeClick (data) {
      console.log(data)
    },
    // 分配权限确认事件
    async onAssignConfirm () {
      // let ids = this.$refs.assignTree.getCheckedKeys();
      // console.log(ids)
      // let idsss = this.$refs.assignTree.getHalfCheckedKeys();
      // console.log(idsss)
      const listId = this.$refs.assignTree
        .getCheckedKeys()
        .concat(this.$refs.assignTree.getHalfCheckedKeys())
      console.log(listId)
      const parm = {
        roleId: this.roleId,
        list: listId
      }
      const res = await assignSaveApi(parm)
      if (res && res.code == 200) {
        this.assignDialog.visible = false
        this.$message.success(res.msg)
      }
    },
    // 分配权限取消事件
    onAssignClose () {
      this.assignDialog.visible = false
    },
    // 分配权限的属性结构查询 处理数据 能实现权限勾选
    async assignRole (row) {
      // 防止this指向的不是vue实例对象
      const that = this
      this.roleId = row.id
      const parm = {
        roleId: row.id,
        userId: this.$store.getters.userId
      }
      const res = await getAssignTreeApi(parm)
      if (res && res.code == 200) {
        // 当前登录用户所拥有的所有权限
        const menuList = res.data.listmenu
        // 当前被分配的角色所拥有的权限
        const selectIds = res.data.checkList
        // 进行一次递归 提取出末级的递归方法变量
        const { setLeaf } = leafUtils()
        // 判断是否末级(设置末级状态位) setLeaf实际上是递归的方法
        const newMenuList = setLeaf(menuList)
        // 把处理好的末级树形结构赋值给页面 渲染出来
        this.assignTreeData = newMenuList
        // 准备第二次递归 勾选树形结构的内容
        this.$nextTick(() => {
          // 这里通过ref绑定处理好末级的树形结构 注意要this.$nextTick渲染后再调用 nodes是通过vue实例拿到的渲染好的树形结构
          const nodes = that.$refs.assignTree.children
          // 进行第二次递归处理 nodes是通过vue实例拿到的树形结构 selectIds是当前角色用户选中权限的id合集 (权限选中数组) that是当前内容的this指向 防止this指错
          that.setChild(nodes, selectIds, that)
          console.log(nodes)
        })
      }
      // 打开弹出层(可删)
      this.assignDialog.visible = true
      this.assignDialog.title = '为【' + row.name + '】分配权限'
    },
    setChild (childNodes, selectIds, that) {
      // 这里不要使用this 要使用上个方法传来的that 以防止this指向错误
      // 判断树形结构是否存在且不小于0
      if (childNodes && childNodes.length > 0) {
        // eslint-disable-next-line no-lone-blocks
        // 遍历树形结构 需要调用element getNode()方法 拿到每个node (每个节点的内容 也就是包含一级二级三级都拿出来)
        for (let j = 0; j < childNodes.length; j++) {
          // 拿到树形结构中的每个node (每个节点的内容 也就是包含一级二级三级都拿出来)
          var node = that.$refs.assignTree.getNode(childNodes[j])
          // 判断(权限选中数组)是否存在 且长度不小于0
          if (selectIds && selectIds.length > 0) {
            // 遍历(权限选中数组) 那存储的所有权限选中id 去树形结构每个节点中的id其匹配
            for (let h = 0; h < selectIds.length; h++) {
              // 如果匹配到了相同的id 说明具备该权限 需要处于选中状态
              if (selectIds[h] == childNodes[j].id) {
                // 这里来判断是否为末级 (通过第一次遍历修改open状态)
                if (childNodes[j].open) {
                  // 通过调用element setChecked()方法 把未勾选变成已勾选状态 node是一级二级三级都拿出来
                  that.$refs.assignTree.setChecked(node, true)
                  // 不用return返回 打断即可
                  break
                }
              }
            }
          }
          // 这里进行判断 如果节点存在children(二级三级) 就继续递归
          if (childNodes[j].children) {
            // 携带所需要的参数childNodes[j](每层数据) selectIds(权限选中数组) that(当前指向)
            that.setChild(childNodes[j].children, selectIds, that)
          }
        }
      }
    },
    // 新增或编辑关闭事件
    onClose () {
      this.addDialog.visible = false
    },
    // 新增或编辑确认事件
    onConfirm () {
      this.$refs.addRoleForm.validate(async (valid) => {
        if (valid) {
          this.addRoleModule.createUser = this.$store.getters.userId
          let res = null
          if (this.addRoleModule.editType == '0') {
            // 新增
            res = await addRoleApi(this.addRoleModule)
          } else {
            res = await editRoleApi(this.addRoleModule)
          }
          if (res && res.code == 200) {
            // 刷新列表
            this.getRoleList(this.parms)
            this.$message.success(res.msg)
            this.addDialog.visible = false
          }
        }
      })
    },
    // 新增按钮
    addRole () {
      // 清空表单数据
      this.$resetForm('addRoleForm', this.addRoleModule)
      this.addRoleModule.editType = '0'
      // 设置弹框属性
      this.addDialog.title = '新增角色'
      this.addDialog.visible = true
    },
    // 取消按钮
    cacelList () {
      this.parms.currentPage = 1
      this.parms.name = ''
      this.getRoleList(this.parms)
    },
    // 查询按钮
    searchList () {
      this.parms.currentPage = 1
      this.getRoleList(this.parms)
    },
    currentChange (val) {
      this.parms.currentPage = val
      this.getRoleList(this.parms)
      console.log('当前页')
      console.log(val)
    },
    sizeChange (val) {
      console.log('页容量')
      console.log(val)
      this.parms.currentPage = 1
      this.parms.pageSize = val
      this.getRoleList(this.parms)
    },
    // 删除按钮
    async deleteRole (row) {
      console.log(row)
      const confrim = await this.$myconfirm('确定删除该数据吗？')
      if (confrim) {
        const parm = {
          id: row.id
        }
        const res = await deleteRoleApi(parm)
        if (res && res.code == 200) {
          // 刷新列表
          this.getRoleList(this.parms)
          this.$message.success(res.msg)
        }
      }
    },
    // 编辑按钮
    editRole (row) {
      // 清空表单
      this.$resetForm('addRoleForm', this.addRoleModule)
      // 设置弹框属性
      this.addDialog.title = '编辑角色'
      this.addDialog.visible = true
      // 标识 编辑
      this.addRoleModule.editType = '1'
      // 把当前点击的行数据复制到表单数据域
      this.$objCoppy(row, this.addRoleModule)
      console.log(row)
    },
    // 获取角色列表
    async getRoleList () {
      const res = await getRoleListApi(this.parms)
      if (res && res.code == 200) {
        this.roleList = res.data.records
        this.parms.total = res.data.total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
